import React, { useCallback, useContext, useState } from 'react';
import { AutoComplete, AutoCompleteProps, Col } from 'antd';
import { ProForm, ProFormContext, ProFormItem } from '@ant-design/pro-components';
import EditOrReadOnlyContext = ProForm.EditOrReadOnlyContext;

// 定义组件的 Props 类型
interface ProFormAutoCompleteProps {
  name: string;
  label: string;
  rules?: any[];
  options?: { value: string; label: string }[];
  placeholder?: string;
  disabled?: boolean;
  // 如果需要异步搜索，可以添加相关 props
  // fetchOptions?: (value: string) => Promise<{ value: string; label: string }[]>;
  // debounceTimeout?: number;
  [key: string]: any; // 其他可能透传的属性
}

const ProFormAutoComplete: React.FC<ProFormAutoCompleteProps & AutoCompleteProps> = ( props ) => {
  const {
    name,
    label,
    rules,
    placeholder,
    disabled = false,
    colProps = {},
    formItemProps = {},
    debounceTimeout = 500,
    search,
    // fetchOptions,
    // debounceTimeout = 800,
    ...restProps // 接收其他属性
  } = props;
  const modeContext = useContext(EditOrReadOnlyContext);
  const readonly = modeContext.mode === 'read';
  const [options, setOptions] = useState<AutoCompleteProps['options']>([]);
  const proFormContext = useContext(ProFormContext);
  let value = proFormContext?.getFieldFormatValue && proFormContext.getFieldFormatValue(name) || '--';
  const handleSearch = useCallback(
    (async ( searchValue?: string ) => {
      if (!search) return;
      try {
        const newOptions = await search(searchValue);
        setOptions(newOptions);
      } catch (error) {
        console.error('Fetch options failed:', error);
      }
    }),
    []
  );

  return (
    <Col xs={24} {...colProps}>
      <ProFormItem key={name} name={name} label={label} rules={rules} {...formItemProps}>
        {
          !readonly ? <AutoComplete
            options={options}
            placeholder={placeholder}
            disabled={disabled}
            onSearch={handleSearch}
            onFocus={() => handleSearch()}
            filterOption={( inputValue, option: any ) =>
              option?.value?.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
            }
            // 其他 AutoComplete 的配置项可以在这里透传
            {...restProps}// 允许通过 fieldProps 传递更多特定配置
          /> : value
        }

      </ProFormItem>
    </Col>
  );
};

export default ProFormAutoComplete;
